package org.tinygroup.bizframe.aop.xmlfileparser;

import java.io.InputStream;

import org.tinygroup.bizframe.aop.config.base.Extensions;
import org.tinygroup.fileresolver.impl.AbstractFileProcessor;
import org.tinygroup.logger.LogLevel;
import org.tinygroup.vfs.FileObject;
import org.tinygroup.xstream.XStreamFactory;

import com.thoughtworks.xstream.XStream;

/**
 * xml文件处理器器
 */
public class ExtensionActionFileProcessor extends AbstractFileProcessor {

    private static final String EXTENSION_EXT_FILENAME = ".extension-action.xml";
    private ExtensionActionXmlManager manager;

    public void setManager(ExtensionActionXmlManager manager) {
        this.manager = manager;
    }

    protected boolean checkMatch(FileObject fileObject) {
        return fileObject.getFileName().endsWith(EXTENSION_EXT_FILENAME);
    }

    public void process() {
        XStream stream = XStreamFactory.getXStream(ExtensionActionXmlManager.XSTEAM_PACKAGE_NAME);
        for (FileObject fileObject : deleteList) {
            LOGGER.logMessage(LogLevel.INFO, "正在移除extensions配置文件[{0}]", fileObject.getAbsolutePath());
            Extensions extensions = (Extensions) caches.get(fileObject.getAbsolutePath());
            if (extensions != null) {
                manager.removeExtensions(extensions);
                caches.remove(fileObject.getAbsolutePath());
            }
            LOGGER.logMessage(LogLevel.INFO, "移除extensions配置文件[{0}]结束", fileObject.getAbsolutePath());
        }
        for (FileObject fileObject : changeList) {
            LOGGER.logMessage(LogLevel.INFO, "正在加载extensions配置文件[{0}]", fileObject.getAbsolutePath());
            Extensions oldMatcher = (Extensions) caches.get(fileObject.getAbsolutePath());
            if (oldMatcher != null) {
                manager.removeExtensions(oldMatcher);
            }
            InputStream inputStream = fileObject.getInputStream();
            Extensions matcher = (Extensions) stream.fromXML(inputStream);
            manager.addExtensions(matcher);
            caches.put(fileObject.getAbsolutePath(), matcher);
            LOGGER.logMessage(LogLevel.INFO, "加载extensions配置文件[{0}]结束", fileObject.getAbsolutePath());
        }
    }
}
